from django.http import JsonResponse
from aliyunsdkcore.client import AcsClient 
from aliyunsdkcore.request import CommonRequest
from h5api.settings import ACCESS_KEY_ID, ACCESS_KEY_SECRET, CODE_MESSAGE
import hashlib
import time

def resultResponse(code=200,err_Msg="",data=None,_list=False):
    if _list:
        returnData = dict()
        returnData['data'] = data
        returnData['code'] = code
        returnData['message'] = CODE_MESSAGE[str(code)]
        return JsonResponse(returnData)
    if not data:
        data = dict()
    data['code'] = code 
    data['message'] = CODE_MESSAGE[str(code)]
    if code == 700:
        data['message'] = err_Msg
    return JsonResponse(data)


def md5(password):
    return hashlib.md5(password.encode("utf-8")).hexdigest()

def getClassData(request,fields=[]):
    data = dict()
    for field in fields:
        data[field] = request.data.get(field,None)
    return data

def createOrderId():
    return str(int(time.time()*1000))+str(int(time.perf_counter()*1000000))

'''
发送短信验证码
'''
def sendPhoneTextMessage(name,order,contact,recivePhoneNum):
    client = AcsClient(ACCESS_KEY_ID,ACCESS_KEY_SECRET,'cn-hangzhou')
    templateParam = str({'name':name,'order':order,'contact':contact})
    request = CommonRequest()
    request.set_accept_format("json")
    request.set_domain("dysmsapi.aliyuncs.com")
    request.set_method("POST")
    request.set_protocol_type("https")
    request.set_version("2017-05-25")
    request.set_action_name("SendSms")

    request.add_query_param("RegionId","cn-hangzhou")
    request.add_query_param("PhoneNumbers",recivePhoneNum)
    request.add_query_param("SignName","言恒书虫")
    request.add_query_param("TemplateCode","SMS_232919291")
    request.add_query_param("TemplateParam",templateParam)
    response = client.do_action(request)
    
    return str(response,encoding="utf-8")
    